import os
import matplotlib.pyplot as plt
import PySimpleGUI as sg
import image_util

def gen_mask_data(values,percentage_center, percentage_edge):
    # 生成mask
    img_w = int(values['-image_shape-'])
    img_h = img_w
    single_mask_arr = image_util.get_linear_sampling_mask(imageshape=(img_w, img_h),
                                               center_sample_ratio=percentage_center,
                                               edge_sample_ratio=percentage_edge)
    return single_mask_arr

if __name__ == '__main__':
    col1 = sg.Column([
        [sg.Frame('输入：', [
                [sg.Text('输入格式：', size=(8, 1)),
                sg.Combo(values=['1D展开并连接的频域数据', '2D频域数据', '1D图像数据', '2D图像数据'],
                        default_value='1D展开并连接的频域数据',
                        enable_events=True,
                        size=(50, 1), k='-input_format-')],
               [sg.Text('输入文件：', size=(8, 1)),
               sg.InputText('', key='-input_mat-', size=(45, 1)),
               sg.Button('打开', key='-btn_open_mat-')],
               [sg.Text('图像尺寸：', size=(8,1)),
                sg.Combo(values=[64,128,256,384,512],
                         default_value=64,
                         enable_events=True,
                         size=(50, 1), k='-image_shape-')],
                [sg.Text('图像shape：', size=(12, 1)),sg.Text('', key='-image_shapeinfo-',size=(32,1) ),
                 sg.Button('读取shape信息', key='-btn_readimginfo-')],
          ],
        )]
    ])

    col2 = sg.Column([
        [sg.Frame('输出：',[
                [sg.Text('输出格式：', size=(8, 1)),
                 sg.Combo(values=['1D展开并连接的频域数据', '2D频域数据', '1D图像数据', '2D图像数据'],
                          default_value='2D图像数据',
                          enable_events=True,
                          size=(45, 1), k='-output_format-')],
                [sg.Text('输出文件：', size=(8, 1)),
                 sg.InputText('', key='-output_mat-', size=(45, 1)),
                 sg.Button('保存', key='-btn_save_mat-')],
                [sg.Text('shift频率：', size=(18, 1)),
                 sg.Radio('是', group_id='-radio_shift-', key='-shift_yes-', default=True, enable_events=True),
                 sg.Radio('否', group_id='-radio_shift-', key='-shift_no-', enable_events=True)],
                [sg.Text('shift在变换之前：', size=(18, 1)),
                 sg.Radio('是', group_id='-radio_shift_first-', key='-shift_first_yes-', enable_events=True),
                 sg.Radio('否', group_id='-radio_shift_first-', key='-shift_first_no-', default=True, enable_events=True)],
            ]
        )]
    ])

    col_mask = sg.Column([
        [sg.Frame('欠采样模板',[
                [sg.Text('掩模中心采样：', size=(12, 1), justification='left'),
                 sg.Slider(key='-percentage_center-', range=(10, 100), size=(30, 20),
                           default_value=16, orientation='horizontal', enable_events=True)],
                [sg.Text('掩模边缘采样：', size=(12, 1), justification='left'),
                 sg.Slider(key='-percentage_edge-', range=(10, 100), size=(30, 20),
                           default_value=30, orientation='horizontal', enable_events=True)],
                [sg.Button('绘制掩膜', key='-plot_mask-')],
            ]
        )]
    ])

    layout = [    [col1],
                  [col_mask],
                  [col2],
                  [sg.Button('转换', key='-btn_convert-'), sg.Text('',key='-txt_info-', text_color='red')],
              ]

    window = sg.Window('【转换图像格式】并【执行频域欠采样】', layout, finalize=True, size=(600,550),
                       element_justification='left', font='宋体 13')
    single_mask_arr = None
    # 下面变量的默认值要与界面的一致，否则程序逻辑不正确
    whether_shift = True
    shift_first = False
    percentage_center = 0.16
    percentage_edge = 0.3
    while True:
        event, values = window.read()
        # print(f'{event=}')
        if event == sg.WINDOW_CLOSED:
            break
        if event=='-plot_mask-':
            print(f'{percentage_center=}')
            print(f'{percentage_edge=}','\n')
            single_mask_arr = gen_mask_data(values, percentage_center, percentage_edge)
            if single_mask_arr is not None:
                plt.subplot(1, 1, 1)
                plt.imshow(single_mask_arr, 'gray', origin='lower')
                plt.show(block=False)
                print('show mask')
        if event=='-btn_convert-':
            img_w = int(values['-image_shape-'])
            img_h = img_w
            single_mask_arr = gen_mask_data(values, percentage_center, percentage_edge)
            window['-txt_info-'].update('')
            if values['-output_mat-'] is None or values['-input_mat-'] is None \
                or values['-input_mat-'].strip()=='' or values['-output_mat-'].strip()=='' \
                   or not os.path.isfile(values['-input_mat-'].strip()):
                continue
            else:
                load_file_path = values['-input_mat-'].strip()
                saved_file_path = values['-output_mat-'].strip()

            if values['-input_format-']== '1D展开并连接的频域数据' and values['-output_format-']=='2D频域数据':
                pass
            elif values['-input_format-']== '1D展开并连接的频域数据' and values['-output_format-']=='2D图像数据':
                freq1d_to_pic2d(load_file_path, saved_file_path,single_mask_arr,(img_w,img_h),whether_shift,shift_first)

            elif values['-input_format-']== '2D频域数据' and values['-output_format-']=='1D展开并连接的频域数据':
                pass
            elif values['-input_format-']== '2D频域数据' and values['-output_format-']=='2D图像数据':
                freq2d_to_pic2d(load_file_path, saved_file_path,single_mask_arr,(img_w,img_h),whether_shift,shift_first)

            elif values['-input_format-'] == '1D图像数据' and values['-output_format-'] == '2D图像数据':
                pic1d_to_pic2d(load_file_path, saved_file_path, single_mask_arr, (img_w,img_h),whether_shift,shift_first)

            elif values['-input_format-']== '2D图像数据' and values['-output_format-']=='1D展开并连接的频域数据':
                pass
            elif values['-input_format-']== '2D图像数据' and values['-output_format-']=='2D频域数据':
                pass
            elif values['-input_format-']== '2D图像数据' and values['-output_format-']=='2D图像数据':
                pic2d_to_pic2d(load_file_path, saved_file_path, single_mask_arr, (img_w,img_h))

            window['-txt_info-'].update('转换完成！')
        elif event=='-btn_open_mat-':
            chosen_load_file_path = sg.popup_get_file('请选择mat文件',
                                                '请选择mat文件',
                                                '',
                                                '.mat',
                                                file_types=(("Mat Files", ". mat"),)
                                               )
            window['-input_mat-'].update(chosen_load_file_path)
        elif event=='-btn_readimginfo-':
            window['-txt_info-'].update('')
            if values['-input_mat-'] is not None and values['-input_mat-'].strip()!='':
                in_mat_filepath=values['-input_mat-']
                in_mat_data = load_mat(in_mat_filepath)
                window['-image_shapeinfo-'].update(str(in_mat_data.shape))
        elif event=='-btn_save_mat-':
            window['-txt_info-'].update('')
            chosen_saved_file_path = sg.popup_get_file('保存文件',
                                                '保存文件',
                                                '',
                                                default_extension="mat",
                                                save_as=True,
                                                file_types=(("Mat Files", ". mat"),)
                                               )
            window['-output_mat-'].update(chosen_saved_file_path)
        elif event=='-shift_yes-':
            whether_shift=True
        elif event=='-shift_no-':
            whether_shift=False
        elif event=='-shift_first_yes-':
            shift_first=True
        elif event=='-shift_first_no-':
            shift_first=False
        elif event=='-percentage_center-':
            percentage_center = int(values['-percentage_center-']) / 100.0
        elif event=='-percentage_edge-':
            percentage_edge = int(values['-percentage_edge-']) / 100.0
    window.close()